package com.sys.utils;

import com.sys.entity.SysPersonal;
import com.bhudy.base.QueryFilter;
import com.sys.entity.SysPlugin;
import com.sys.service.SysPluginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Map;
import java.util.Properties;

/**
 * 执行发送邮件
 * Created by Administrator on 2019/11/5/005.
 */
@Component
public final class MailUtils {
    @Autowired
    private MailUtils(SysPluginService sysPluginService) {
        MailUtils.sysPluginService = sysPluginService;
    }

    private static SysPluginService sysPluginService;

    @Value("${bhudy.ip}")
    private void setIp(String ip) {
        this.ip = ip;
    }

    private static String ip;

    /**
     * 发送邮件
     *
     * @param title   标题
     * @param content 内容
     * @param userId  接受邮箱地址
     * @throws MessagingException
     */
    public static void send(Long userId, String title, String content) {
        try {
            QueryFilter queryFilter = new QueryFilter().and("where id = (select res_personal_id from sys_user where user_id = ?)", userId);
            SysPersonal sysPersonal = sysPluginService.find(SysPersonal.class, queryFilter); // 获取用户信息
            if (sysPersonal == null || sysPersonal.getEmail() == null || sysPersonal.getEmail().equals("")) return;

            Map<String, String> sysPluginDataMap = sysPluginService.getSysPluginDataByType(SysPlugin.MAIL_KEY);//获取邮件配置
            StringBuffer contentSb = new StringBuffer();
            contentSb.append("<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><meta name=\"viewport\"content=\"width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0\"><title>健玛医疗运营平台邮件</title><style>*{padding:0;margin:0}ul{margin:0;padding:0}a{color:#888;text-decoration:none!important}.fl{float:left}.fr{float:right}#wrap{margin:0 auto;width:700px;border:1px solid#eee}#header{background-color:#3c8dbc;overflow:hidden;font-size:15px}#logo{margin:0 20px;line-height:40px;color:#fff}#logo img,#logo span{vertical-align:middle;margin:0 1px}.top-nav ul li{float:left;list-style:none}.top-nav ul li a{color:#fff;line-height:42px;padding:0 20px;display:block;text-decoration:none}.top-nav ul li a:hover{background-color:#ddd;color:#111}#content{padding:10px}.content_icon{height:80px;width:40px;max-width:50px;margin-right:10px;vertical-align:middle;line-height:40px;text-align:center}.content_icon img{margin-top:10px;max-width:30px}.content_msg{width:85%;line-height:30px}#floor{height:60px;line-height:60px;background-color:#f3f3f3;box-sizing:border-box;padding-left:20px;color:#3c3c3c;font-size:12px}</style></head><body><div id=\"wrap\"><div id=\"header\"><div class=\"fl\"id='logo'><span>健玛医疗运营平台</span></div></div><div id=\"content\"><p><br><br>尊敬的<span>${username}</span>用户,您好:</p><div style=\"overflow: hidden;margin-left: 35px\"><br><br><div class=\"fl content_icon\"><img src=\"\"></div><span class=\"fl content_msg\">${content}</span></div><p><br><br>健玛医疗运营平台<br>技术支持：jmoms_support@163.com</p><p><br><br>广州健玛医疗器械有限公司<br><br></p><p style=\"border-top: 1px dashed #999;\"><span style=\"line-height: 20px;color:#999;font-size: 12px;\">此为系统邮件请勿回复</span></p></div><div id=\"floor\"><span>Copyright©广州健玛医疗器械有限公司.最终解释权</span></div></div></body></html>");


            String contents = contentSb.toString();
            contents = contents.replace("${content}", content);
            contents = contents.replace("${ip}", ip);
            contents = contents.replace("${username}", sysPersonal.getName());


            JavaMailSenderImpl jms = new JavaMailSenderImpl();
            jms.setHost(sysPluginDataMap.get(SysPlugin.smtpServer));
            jms.setPort(Utils.formatInt(sysPluginDataMap.get(SysPlugin.port)));
            jms.setUsername(sysPluginDataMap.get(SysPlugin.userName));
            jms.setPassword(sysPluginDataMap.get(SysPlugin.userPwd));
            jms.setDefaultEncoding("Utf-8");
            Properties p = new Properties();
            p.setProperty("mail.smtp.auth", "true");
            jms.setJavaMailProperties(p);

            MimeMessage mimeMessage = jms.createMimeMessage();
            // 设置收件人的邮箱
            InternetAddress to = new InternetAddress(sysPersonal.getEmail());
            mimeMessage.setRecipient(Message.RecipientType.TO, to);

            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(sysPluginDataMap.get(SysPlugin.userName)); //sender为自定义显示发件人名称
            helper.setTo(to);
            helper.setSubject("【健玛医疗运营平台】" + title);
            helper.setText(contents, true);
            jms.send(mimeMessage); //邮件发送完毕
        } catch (AddressException e) {
            Utils.loggerError(MailUtils.class, e);
        } catch (MessagingException e) {
            Utils.loggerError(MailUtils.class, e);
        }
    }

    private static String logoImg = "";

}
